package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.serve.dto.CheckInApplyDto;
import com.zzyl.serve.dto.CheckInElderDto;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        // 判断老人是否已经入住
        // 通过身份证号查询老人
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }

//更新床位的状态  已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

// 保存或更新老人数据
        elder = insertUpdateElder(bed, dto.getCheckInElderDto());
        // 生成合同编号
        String contractNo = "HT" + DateUtils.dateTimeNow("yyyyMMdd") + String.format("%06d", new java.util.Random().nextInt(999999));

        // 新增签约办理
        insertContract(contractNo, elder, dto);
        // 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);

        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);


    }


    private void insertCheckInConfig(Long id, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增合同
     *
     * @param contractNo
     * @param elder
     * @param dto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto dto) {


        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Long status = Long.valueOf(checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0);
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param checkInApplyDto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0L);
        checkInMapper.insert(checkIn);
        return checkIn;
    }


    private Elder insertUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        // 准备老人数据
        Elder elder = new Elder();
        // 属性拷贝
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 查询老人信息，（身份证号、状态不为1）
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(elder);
        } else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //老人相关的
        //通过id找到入住配置   拿到老人id
        CheckIn checkIn = checkInMapper.selectCheckInById(id);

        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if (ObjectUtil.isNotEmpty(elder)) {
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder, checkInElderVo);
            checkInElderVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));
            vo.setCheckInElderVo(checkInElderVo);
        }


        //入住配置
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper<>();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);

        if (checkInConfigVo == null) {
            checkInConfigVo = new CheckInConfigVo();
        }

        //补全其他属性
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        vo.setCheckInConfigVo(checkInConfigVo);


        //合同
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(contractWrapper);
        vo.setContract(contract);

        //家属列表
        String otherApplyInfo = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(otherApplyInfo, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVos);

        return vo;
    }

    @Override
    public void updateContractStatus() {
        //1.查询状态=0的以及签约时间大于当前时间的合同，全部更新为1
        LambdaQueryWrapper<Contract> queryWrapper= Wrappers.lambdaQuery();
        queryWrapper.eq(Contract::getStatus,0);
        queryWrapper.le(Contract::getSignDate, LocalDateTime.now());
        List<Contract> contractList = contractMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(contractList)) {
            return;
        }
        //3.更新状态值1
        contractList.forEach(contract -> {
            contract.setStatus(1L);
        });
        //2.批量更新
        // 替换第302行的 updateBatchById(contractList);
        for (Contract contract : contractList) {
            contractMapper.updateById(contract);
        }

    }
}
